# 1.
import pickle, json

a_list = [1, 2, 3, [4, 5, 6]]


# 使用 pickle
def use_pickle():
    f = open("serialize.txt", "wb+")
    pickle.dump(a_list, f)
    f.close()

    f2 = open("serialize.txt", "rb+")
    b_list = pickle.load(f2)
    print(b_list)
    f2.close()


# 使用 json
def use_json():
    f = open("serialize2.txt", "w+")
    json.dump(a_list, f)
    f.close()

    f2 = open("serialize2.txt", "r+")
    b_list = json.load(f2)
    print(b_list)
    f2.close()


# use_pickle()
# use_json()


# 2.
from copy import copy, deepcopy

a_list = [1, 2, 3, 4, [8, 9, 0]]


# 使用浅拷贝
def use_copy():
    '''
    浅拷贝只拷贝外层元素，其他内层仍然是引用地址
    :return:
    '''
    b_list = copy(a_list)
    print(a_list, b_list)  # [1, 2, 3, 4, [8, 9, 0]] [1, 2, 3, 4, [8, 9, 0]]
    print(id(a_list), id(b_list), )  # 39726152 39726216
    print(id(a_list[4]), id(b_list[4]))  # 39547400 39547400


# 使用深拷贝
def use_deepcopy():
    '''
    深拷贝会拷贝所有元素
    :return:
    '''
    b_list = deepcopy(a_list)
    print(a_list, b_list)  # [1, 2, 3, 4, [8, 9, 0]] [1, 2, 3, 4, [8, 9, 0]]
    print(id(a_list), id(b_list))  # 39463944 39464008
    print(id(a_list[4][1]), id(b_list[4][1]))  # 501116640 501116640


# use_copy()
# use_deepcopy()

# 3.
from io import StringIO, BytesIO


def use_stringio():
    # f = StringIO()
    # f.write("hello\n")
    # f.write("Hi\n")
    # f.write("Python")

    f = StringIO("hello\nHi\nPython")
    while True:
        s = f.readline()
        if len(s) == 0:
            break
        print(s.strip())


def use_bytesio():
    # f=BytesIO()
    # f.write("Hello Python".encode("utf-8"))
    # print(f.getvalue().decode("utf-8"))

    f = BytesIO("Hello Python".encode("utf-8"))
    print(f.read().decode("utf-8"))


# use_stringio()
use_bytesio()
